package com.dms.modules.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.modules.community.entity.CommunityPostTag;
import com.dms.modules.community.mapper.CommunityPostTagMapper;
import com.dms.modules.community.service.CommunityPostTagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommunityPostTagServiceImpl extends ServiceImpl<CommunityPostTagMapper, CommunityPostTag> implements CommunityPostTagService {

    @Override
    public List<Long> getTagIdsByPostId(Long postId) {
        try {
            LambdaQueryWrapper<CommunityPostTag> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityPostTag::getPostId, postId)
                  .select(CommunityPostTag::getTagId);
            
            return list(wrapper).stream()
                .map(CommunityPostTag::getTagId)
                .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取帖子标签列表失败: postId={}, error={}", postId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public List<Long> getPostIdsByTagId(Long tagId) {
        try {
            LambdaQueryWrapper<CommunityPostTag> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityPostTag::getTagId, tagId)
                  .select(CommunityPostTag::getPostId);
            
            return list(wrapper).stream()
                .map(CommunityPostTag::getPostId)
                .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取标签帖子列表失败: tagId={}, error={}", tagId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional
    public void deleteByPostId(Long postId) {
        try {
            LambdaQueryWrapper<CommunityPostTag> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityPostTag::getPostId, postId);
            remove(wrapper);
            log.info("删除帖子标签关系成功: postId={}", postId);
        } catch (Exception e) {
            log.error("删除帖子标签关系失败: postId={}, error={}", postId, e.getMessage(), e);
            throw e;
        }
    }
} 